package com.foreveross.chameleon.exhibition;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.webkit.WebView;
import android.widget.TextView;
import com.foreveross.chameleon.base.BslApplication;
import com.foreveross.chameleon.base.BslConfig;
import com.foreveross.chameleon.sandbox.FileInputStream;
import com.foreveross.chameleon.sandbox.FileOutputStream;
import com.foreveross.chameleon.utils.*;

import java.io.*;
import java.io.File;
import java.util.Date;

/**
 * Created by wzq on 14-8-19
 */
public class ActivityEntry extends Activity {
    private Context mCtx;
    private boolean testMode = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_entry);
        mCtx = this;
        tvProgress = (TextView) findViewById(R.id.tv_progress);
        if (testMode) {
            findViewById(R.id.layer_test).setVisibility(View.VISIBLE);
            findViewById(R.id.layer_release).setVisibility(View.GONE);
        }

        //
        new Thread(new Runnable() {
            @Override
            public void run() {
                check();
                init();
                sendToUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initDone();
                    }
                });
            }
        }).start();
    }

    // just test TODO to be delete
    private void check() {
        sendToUiThread("检测状态...");
        StringBuilder sb = new StringBuilder();
        sb.append("\nfirst installation = " + SpTool.getSp().getBoolean(BslConfig.SP_KEY_FIRST_INSTALL, true));
        sb.append("\nwww folder exist = " + new File(BslConfig.WWW_FOLDER_IN_SD).exists());
        // sandbox 模式
        sb.append("\nsandbox mod =" + getResources().getString(R.string.build_config_sandbox));
        // 读取prop文件
        sb.append("\nAES_PASSWORD from prop =" + PropReader.getInstance().getProp("AES_PASSWORD"));
        // AES_PASSWORD
        sb.append("\nAES_PASSWORD from java = " + BslConfig.AES_PASSWORD);
        // 客户端 加密测试
        String str = "你好@#$%^&*";
//        String encryptStr = AesTool.getInstance().encryptString(str);
        String encryptStr = AesTool.encryptString(str);
//        String decryptStr = AesTool.getInstance().decryptString(encryptStr);
        String decryptStr = AesTool.decryptString(encryptStr);
        if (str.equals(decryptStr)) {
            sb.append("\n客户端 加解密String ok");
        } else {
            sb.append("\n客户端 加解密String 失败");
        }
        // 脚本加密，java解密
//        AssetManager assetManager = BslApplication.getInstance().getAssets();
        AssetManager assetManager = getAssets();
        String fileName = "www/cordova.js";//www/test_crypt.txt
        String deStr = null;
        try {
            InputStream src = assetManager.open(fileName);
//            InputStream dst = AesTool.getInstance().decryptStream(src);
            InputStream dst = AesTool.decryptStream(src);
            if (dst != null) {
                deStr = IOUtils.stream2String(dst, "UTF-8");
            } else {
                sb.append("\ndecryptStream fail");
            }
        } catch (IOException e) {
            e.printStackTrace();
            sb.append("\n" + fileName + "不存在");
        }
        if (deStr == null) {
            sb.append("\n" + fileName + "解密失败");
        } else {
            sb.append("\n" + fileName +"解密成功\n"+ deStr.substring(0, 100));
        }

        // TODO:直接通过file来读写加密文本
        if (BslConfig.IS_SANDBOX) {
            File f = new File(BslConfig.WWW_FOLDER_IN_SD, "test_wr.txt");
            String strNow = new Date().toString();
            try {
                if (f.exists()) { // append
                    FileOutputStream out = new FileOutputStream(f);
                    out.append("\n" + strNow);
                    out.close();
                } else { // write
                    f.createNewFile();
                    FileOutputStream out = new FileOutputStream(f);
                    byte[] bytes = IOUtils.string2Bytes(strNow, "utf-8");
                    out.write(bytes);
                    out.close();
                }
                // read
                FileInputStream stream = new com.foreveross.chameleon.sandbox.FileInputStream(f);
                String content = IOUtils.stream2String(stream, "utf-8");
                sb.append("\ntest_wr.txt=" + content);
                stream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        // folder位置
        sb.append("\nwww folder = " + BslConfig.WWW_FOLDER_IN_SD);
        // provider
        sb.append("\nproviderName = " + getResources().getString(R.string.providerName));
        sb.append("\nproviderAuth = " + getResources().getString(R.string.providerAuth));

        // 打印输出
        final String checkInfo = sb.toString();
        sendToUiThread(new Runnable() {
            @Override
            public void run() {
                TextView tvCheck = (TextView) findViewById(R.id.tv_check);
                tvCheck.setText(checkInfo);
            }
        });
        AppLog.i(checkInfo);
    }

    private void init() {
        sendToUiThread("初始化...");
        if (!BslConfig.IS_SANDBOX) {
            // we shall do nothing
            AppLog.i(" not sandbox mod ");
            return;
        }

        // sandbox mode : copy and update
        AppLog.i("sandbox mod ");
        sendToUiThread("拷贝文件...");
        boolean isFirst = SpTool.getSp().getBoolean(BslConfig.SP_KEY_FIRST_INSTALL, true);
        boolean isCopyAll = isFirst || !new File(BslConfig.WWW_FOLDER_IN_SD).exists();
        if (isCopyAll) {
            AppLog.i("copyAll,isFirst=" + isFirst + ",wwwFolder=" + BslConfig.WWW_FOLDER_IN_SD);
            ActivityEntryAssit.copyAll(mCtx);
        } else {
            int preSavedVer = SpTool.getSp().getInt(BslConfig.SP_KEY_APPVERSION, 0);
            int currVer = AndroidTool.getVersionCode();
            AppLog.i("preSavedVer=" + preSavedVer + ",currVer=" + currVer);
            boolean isUpdateCopy = currVer > preSavedVer;
            if (isUpdateCopy) {
                AppLog.i("copyByVersion");
                ActivityEntryAssit.copyByVersion(mCtx);
            } else {
                AppLog.i("do not neet copy anything");
            }
        }
    }

    private void initDone() {
        sendToUiThread("初始化 over");

        // 初次启动
        int showTime = 3000;
        if (SpTool.getSp().getBoolean("first_start", true)) {
            SpTool.getSp().write("first_start", false);
        } else {
            showTime = 0;
        }

        // 跳转
        if (!testMode) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    goNextAct();
                }
            }, showTime);
            return;
        }

        // 测试provider
        WebView webView = (WebView) findViewById(R.id.web_test);
        if (BslConfig.IS_SANDBOX) {
            String url1 = BslConfig.SCHEME_PROVIDER + BslConfig.WWW_FOLDER_IN_SD + "/index.html";
            webView.loadUrl(url1);
        } else {
            String url2 = BslConfig.SCHEME_PROVIDER + "/" + BslConfig.ASSETS_WWW_FOLDER + "/index.html";
            webView.loadUrl(url2);
        }


        // record all
        SpTool spTool = SpTool.getSp();
        spTool.write(BslConfig.SP_KEY_FIRST_INSTALL, false);
        spTool.write(BslConfig.SP_KEY_APPVERSION, AndroidTool.getVersionCode());
        findViewById(R.id.pb_init).setVisibility(View.INVISIBLE);

        View btnInitDone = findViewById(R.id.btn_init_done);
        btnInitDone.setVisibility(View.VISIBLE);
        btnInitDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goNextAct();
            }
        });

        // 启动mdm
        // MdmCmdExecutor.getInstance().active((Activity) mCtx);
    }

    private void goNextAct() {
        Intent intent = new Intent(mCtx, chameleon.class);
        mCtx.startActivity(intent);
        finish();
    }


//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode == MdmCmdExecutor.REQUEST_CODE_MDM) {
//            if (resultCode == RESULT_OK) {
//                AppLog.i("mdm 激活成功");
//            } else {
//                AppLog.i("mdm 未激活");
//                Toast.makeText(mCtx, "mdm 未激活，不允许使用本APP", Toast.LENGTH_SHORT).show();
//                finish();
//            }
//        }
//    }

    private void sendToUiThread(final String str) {
        uiHandler.post(new Runnable() {
            @Override
            public void run() {
                tvProgress.setText(str);
            }
        });
    }

    private void sendToUiThread(Runnable r) {
        uiHandler.post(r);
    }

    private TextView tvProgress;
    private Handler uiHandler = new Handler(Looper.getMainLooper());
}
